package cn.edu.njuit.server.ugcnote.ugcnoteserver.service.impl;

import cn.edu.njuit.server.ugcnote.ugcnoteserver.entity.UserInfo;
import cn.edu.njuit.server.ugcnote.ugcnoteserver.repository.UserInfoRepository;
import cn.edu.njuit.server.ugcnote.ugcnoteserver.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    UserInfoRepository userInfoRepository;

    @Override
    public UserInfo getUser(String userName) {
        return userInfoRepository.findByUserName(userName);
    }

    @Override
    public UserInfo regAccount(String login, String password,String nickname) throws Exception {
        //根据登录名查询账户是否存在
        UserInfo account = getUser(login);
        if(account!=null){
            throw new Exception("登录名已存在，注册失败");
        }
        account = new UserInfo();
        account.setUserStatus("1");
        account.setUserName(login);
        account.setUserNickname(nickname);
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        account.setUserPassword(encoder.encode(password));
        account.setRegisterTime(LocalDateTime.now());
        account=this.userInfoRepository.save(account);
        return account;
    }
}
